﻿//  Key Tracker - An application to keep track of product keys.
//
//  Copyright (c) 2009  Shawn Rakowski
//
//  Permission is hereby granted, free of charge, to any person
//  obtaining a copy of this software and associated documentation
//  files (the "Software"), to deal in the Software without
//  restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the
//  Software is furnished to do so, subject to the following
//  conditions:
//
//  The above copyright notice and this permission notice shall be
//  included in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//  OTHER DEALINGS IN THE SOFTWARE.
// --------------------------------------------------------------------------//
/*      MainForm.cs 
 *      
 * 
 *      Key Tracker Project   
 *      
 *      CODE FILE DESCRIPTION:
 *      
 *          This code file contains all the classes and methods for the
 *          main form that is loaded at start up.
 * 
 *      AUTHOR(S):
 *      
 *          Shawn Rakowski
 * 
 *      CLASSES:
 *      
 *          MainForm : Form
 *      
 *      MODIFICATION HISTORY:
 *      
 *          06-AUG-2008     Shawn R.    New Program.
 *          10-AUG-2008     Shawn R.    Added new/open dialogue boxes to methods.
 *                                      Added handling for use of replicated databases.
 *          14-AUG-2008     Shawn R.    Added Auto-Connect to database feature.
 *          16-MAR-2008     Shawn R.    Fixed so copy button enables/disabled correctly, moved
 *                                      the export to file, eliminated the help and data menu items.
 *          17-MAR-2008     Shawn R.    Changed font and made changed to the auto-connect so it functions
 *                                      correctly.
 * 
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KeyTracker.Classes;

namespace KeyTracker
{
    public partial class MainForm : Form
    {
        #region Class Level Variables

        KeyTrackerDatabase keyTrackerDatabase = new KeyTrackerDatabase();

        bool installMode = false;

        #endregion

        #region MainForm Constructor/Methods

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.EnableDatabaseAutoConnect)
            {
                if (Properties.Settings.Default.DefaultDatabaseFileName != "" &&
                    System.IO.File.Exists(Properties.Settings.Default.DefaultDatabaseFileName))
                {
                    keyTrackerDatabase.UseReplicatedDatabase = Properties.Settings.Default.UseRelplicatedDatabase;
                    keyTrackerDatabase.OpenDB(Properties.Settings.Default.DefaultDatabaseFileName);
                    if (!keyTrackerDatabase.DBOpen)
                        Properties.Settings.Default.DefaultDatabaseFileName = "";
                }
                UpdateData();
            }
            UpdateUI();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!CloseTheDatabase())
                e.Cancel = true;
        }

        #endregion

        #region Form Event Handlers

        private void connectionFileToolStripMenuItem_Click(object sender, 
            EventArgs e)
        {
            OpenFileDialog
                openDB = new OpenFileDialog();

            if (!keyTrackerDatabase.DBOpen)
            {
                #region Set openDB Dialog Properties

                openDB.Title = "Open existing Key Tracker database...";
                openDB.CheckFileExists = true;
                openDB.Multiselect = false;
                openDB.Filter = "KeyTracker Databases (*.ktdb)|*.ktdb";

                #endregion

                openDB.ShowDialog();

                keyTrackerDatabase.UseReplicatedDatabase = Properties.Settings.Default.UseRelplicatedDatabase;
                keyTrackerDatabase.OpenDB(openDB.FileName);
            }
            else
            {
                CloseTheDatabase();
            }
            UpdateData();
            UpdateUI();
        }

        private void newFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog
                newDB = new SaveFileDialog();
  
            if (keyTrackerDatabase.DBOpen)
            {
                string 
                    message = "Creating a new database will disconnect you from your current database. " + 
                              "Would you like to disconnect from " + System.IO.Path.GetFileName(keyTrackerDatabase.DBFileName) + 
                              " and create a new one?";
                if (MessageBox.Show(message, "Key Tracker", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (!CloseTheDatabase())
                        return;
                }
                else
                    return;
            }

            #region Set newDB Dialog Properties

            newDB.AddExtension = true;
            newDB.Title = "Save New Key Tracker Database As...";
            newDB.Filter = "KeyTracker Databases (*.ktdb)|*.ktdb";
            newDB.ValidateNames = true;
            newDB.OverwritePrompt = true;
            newDB.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            #endregion

            newDB.ShowDialog();

            keyTrackerDatabase.UseReplicatedDatabase = Properties.Settings.Default.UseRelplicatedDatabase;
            keyTrackerDatabase.NewDB(newDB.FileName);
            UpdateData();
            UpdateUI();
        }

        private void exitFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.Save();
            Application.Exit();
        }

        private void exportKeysFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            #region Variable Declarations

            SaveFileDialog
                exportAllKeysDialog = new SaveFileDialog();

            string
                message;

            #endregion

            #region Set Export Dialog Properties

            exportAllKeysDialog.AddExtension = true;
            exportAllKeysDialog.Title = "Export to";
            exportAllKeysDialog.Filter = "Text File (*.txt)|*.txt|" +
                                         "Comma-Seperated Values (*.csv)|*.csv";
            exportAllKeysDialog.ValidateNames = true;
            exportAllKeysDialog.OverwritePrompt = true;
            exportAllKeysDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            #endregion

            exportAllKeysDialog.ShowDialog();

            if (exportAllKeysDialog.FileName != "")
            {
                if (exportAllKeysDialog.FileName.Contains(".txt"))
                {
                    keyTrackerDatabase.ExportAllKeys(exportAllKeysDialog.FileName, (int)EXPORT_FORMATS.TXT);
                }
                else if (exportAllKeysDialog.FileName.Contains(".csv"))
                {
                    keyTrackerDatabase.ExportAllKeys(exportAllKeysDialog.FileName, (int)EXPORT_FORMATS.CSV);
                }
                message = "All product keys successfully exported to " + exportAllKeysDialog.FileName + ".";
                MessageBox.Show(message, "Export All Keys", MessageBoxButtons.OK, MessageBoxIcon.None);
            }
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.Save();
            Application.Exit();
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Forms.AboutKeyTrackerForm
            about = new KeyTracker.Forms.AboutKeyTrackerForm();
            about.ShowDialog();
        }

        private void editKeysButton_Click(object sender, EventArgs e)
        {
            KeyTracker.Forms.EditKeysForm 
                editKeysForm = new KeyTracker.Forms.EditKeysForm(productComboBox.SelectedItem.ToString(),
                                                                   productComboBox.SelectedIndex,
                                                                   keyTrackerDatabase);
            editKeysForm.ShowDialog();
            keysListBox.Items.Clear();
            keysListBox.Items.AddRange(keyTrackerDatabase.GetKeys(productComboBox.SelectedIndex));
            editKeysButton.Enabled = true;
            copyButton.Enabled = false;
        }

        private void productComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            keysListBox.Items.Clear();
            keysListBox.Items.AddRange(keyTrackerDatabase.GetKeys(productComboBox.SelectedIndex));
            if (!editKeysButton.Enabled)
                editKeysButton.Enabled = true;
            copyButton.Enabled = false;
        }

        private void keysListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (keysListBox.SelectedIndex != -1)
                copyButton.Enabled = true;  
            else
                copyButton.Enabled = false;  
        }

        private void copyButton_Click(object sender, EventArgs e)
        {
            if (keysListBox.SelectedIndex != -1)
            {
                Clipboard.SetText(keysListBox.SelectedItem.ToString());
            }
        }

        private void editProductButton_Click(object sender, EventArgs e)
        {
            Forms.EditProductsForm
                editProductsForm = new KeyTracker.Forms.EditProductsForm(keyTrackerDatabase);
            editProductsForm.ShowDialog();
            UpdateData();
        }

        private void settingsClientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Forms.SettingsForm settingsForm = new Forms.SettingsForm();
            settingsForm.ShowDialog();
            if (Properties.Settings.Default.EnableDatabaseAutoConnect &&
                keyTrackerDatabase.DBOpen)
            {
                autoConnectCheckBox.Enabled = true;
            }
            else
            {
                autoConnectCheckBox.Enabled = false;
            }
        }

        private void installModeClientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            mainNotifyIcon.Visible = true;
            this.ShowInTaskbar = false;
            this.Hide();
            installMode = true;
            InstallMode();
        }

        private void exitInstallModeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            installMode = false;
            mainNotifyIcon.Visible = false;
            this.ShowInTaskbar = true;
            this.Show();
        }
        
        private void autoConnectCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (autoConnectCheckBox.Checked && keyTrackerDatabase.DBOpen)
            {
                Properties.Settings.Default.DefaultDatabaseFileName = keyTrackerDatabase.DBFileName;
            }
            else if (!autoConnectCheckBox.Checked && keyTrackerDatabase.DBOpen &&
                     keyTrackerDatabase.DBFileName == Properties.Settings.Default.DefaultDatabaseFileName)
            {
                Properties.Settings.Default.DefaultDatabaseFileName = "";
            }
        }

        #endregion

        #region Additional Methods

        private void UpdateUI()
        {
            if (keyTrackerDatabase.DBOpen)
            {
                connectionFileToolStripMenuItem.Text = "Disconnect from Database";
                String message = "Key Tracker - [FILE]";
                this.Text = message.Replace("[FILE]",
                    System.IO.Path.GetFileNameWithoutExtension(keyTrackerDatabase.DBFileName));
                productLabel.Enabled = true;
                productComboBox.Enabled = true;
                keysLabel.Enabled = true;
                keysListBox.Enabled = true;
                editProductButton.Enabled = true;
                exportKeysFileToolStripMenuItem.Enabled = true;
                installModeClientToolStripMenuItem.Enabled = true;
                if (Properties.Settings.Default.EnableDatabaseAutoConnect)
                    autoConnectCheckBox.Enabled = true;
                if (keyTrackerDatabase.DBFileName == Properties.Settings.Default.DefaultDatabaseFileName)
                    autoConnectCheckBox.Checked = true;
                else
                    autoConnectCheckBox.Checked = false;
            }
            else
            {
                connectionFileToolStripMenuItem.Text = "Connect To Database";
                this.Text = "Key Tracker";
                productLabel.Enabled = false;
                productComboBox.Items.Clear();
                productComboBox.Enabled = false;
                keysLabel.Enabled = false;
                keysListBox.Enabled = false;
                editKeysButton.Enabled = false;
                editProductButton.Enabled = false;
                exportKeysFileToolStripMenuItem.Enabled = false;
                installModeClientToolStripMenuItem.Enabled = false;
                autoConnectCheckBox.Checked = false;
                autoConnectCheckBox.Enabled = false;
                copyButton.Enabled = false;
                editKeysButton.Enabled = false;
            }
        }

        private void UpdateData()
        {
            keysListBox.Items.Clear();
            editKeysButton.Enabled = false;
            copyButton.Enabled = false;
            productComboBox.Items.Clear();
            productComboBox.Text = "";
            productComboBox.Items.AddRange(keyTrackerDatabase.ProductRange);
        }

        private bool CloseTheDatabase()
        {
            string
                message;

            if (keyTrackerDatabase.UsingReplicatedDatabase && keyTrackerDatabase.ChangesHaveBeenMade)
            {
                message = "You are currently using a replicated database. " +
                          "Would you like to commit changes to this database? If you " +
                          "select \"No\" the database will be closed and changes will " +
                          "not be saved.";
                DialogResult result = MessageBox.Show(message, "Replicated Database",
                                        MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                if (result == DialogResult.Yes)
                {
                    keyTrackerDatabase.CloseDB(true);
                }
                else if (result == DialogResult.No)
                {
                    keyTrackerDatabase.CloseDB(false);
                }
                else
                {
                    return false;
                }
            }
            else
            {
                keyTrackerDatabase.CloseDB(true);
            }

            return true;
        }

        private void InstallMode()
        {
            if (installMode)
            {

            }
        }

        #endregion
    }
}
